<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue3 watch - Asynchronous operations</title>
  <style>
    button {
      margin-top: 10px;
    }
  </style>
</head>
<body>
  <h2>Vue3 watch test</h2>
  <hr>
  <div id="app">
    direct message: {{msg}}
    <div>message: {{msg}}</div>
    <button @click="chgMsg">Change Message</button>
    <hr>

    <h4>Asynchronous operations in watch functions</h4>
    <p>
      Ask a yes/no question:
      <input v-model="question" />
    </p>
    <p>{{ answer }}</p>
    <hr>

  </div>

  <script type="text/javascript" src="../_jsvue3/vue.prod.js"></script>
  <script type="module">

    //vue3 demo
    const myApp = {
      setup() {
        // msg
        let msg = Vue.ref('test message')

        function chgMsg() {
          return msg.value += '~'
        }

        Vue.watch(msg, (newValue, oldValue) => {
          console.log('msg is changed: from "', oldValue, '" to "', newValue, '"')
        })

        console.log('setup...')
        // life cycle functions
        Vue.onMounted( () => {
          console.log('mounted...')
        })

        // asynchronous operations in watch functions
        let answerLoad = debounce(getAnswer, 500)

        //   ref: https://v3.cn.vuejs.org/guide/computed.html#%E4%BE%A6%E5%90%AC%E5%99%A8
        
        let question = Vue.ref('')
        let answer = Vue.ref('Questions usually contain a question mark. ^o^')

        Vue.watch(question, (newValue, oldValue) => {
          if (newValue.indexOf('?') >= 0) {
            answer.value = 'Thinking...'
            answerLoad()
          }
        })

        function debounce(func, delay){
          let timer = null
          return function (...args){
            if (timer) {
              clearTimeout(timer)
            }
            timer = setTimeout( () => {
              func.apply(this, args)
            }, delay)
          }
        }        

        function getAnswer() {
          fetch('https://yesno.wtf/api')
            .then( response => response.json() )
            .then( json => {
              console.log(json)
              answer.value = json.answer
            })
            .catch( error => {
              answer.value = 'Error! Could not reach the API. ' + error
            })
        }

        // expose all data & functions
        return {
          msg, chgMsg,
          question, answer
        }
      }
    }

    const app = Vue.createApp(myApp).mount('#app')

  </script>
</body>
</html>